import { BaseContext } from "koa";
import { getRepository } from "typeorm";
import authorize from "../../middleware/authorize";
import { Get, Post, Controller } from "../../middleware/request";
import { Exception } from "../../utils/exception";
// import { User } from "../entity/User";
import { auth as Auth } from "../../utils/auth";
import { today, slicePath, mkdir } from "../../utils/index";
import { upToQiNiu, upToAliOss, upToTxCos } from "../../utils/uploadServer";
import fsa from "fs-extra";
import { PUBLIC_PATCH } from "../../config";
const fs = require("fs");
const path = require("path");
let path_src = "../../public/images/" + today();
@Controller("/api")
export class uploadFileController {
  //   @authorize()
  @Post("/uploadFile")
  async uploadFile(ctx: BaseContext) {
    try {
      const file = ctx.request.files.file;
      // 文件名称
      let FileName = slicePath(file.path, file.name);
      const fileType = file.type.split("\/")[1] || "";
      let filePath = ""
      if(['jpg', 'jpeg', 'jiff', 'png', 'gif'].indexOf(fileType) > -1){
        fsa.ensureDirSync(path.join(PUBLIC_PATCH,`/images/${today()}`));
        filePath = `/images/${today()}/${FileName}`;
      }else if(['mp4', 'mp3', 'avi', 'rmvb'].indexOf(fileType) > -1){
        fsa.ensureDirSync(path.join(PUBLIC_PATCH,`/media/${today()}`));
        filePath = `/media/${today()}/${FileName}`;
      }else{
        return ctx.body = {
          ...Exception(112, "文件格式类型不支持，请重新上传'jpg', 'jpeg', 'jiff', 'png', 'gif','mp4', 'mp3', 'avi', 'rmvb'")
        };
      }
      // 创建可读流
      const render = fs.createReadStream(file.path);
      // 创建写入流
      // let filePath = path.join(__dirname, path_src, FileName);
      const stream = fs.createWriteStream(path.join(PUBLIC_PATCH,filePath));
      render.pipe(stream);
      // const fileUrl = `${today()}/${FileName}`;
      // 上传七牛云
      // const qiniu: any = await upToQiNiu(render, fileUrl)
      //上传到阿里云oss
      // const aliOss:any = await upToAliOss(filePath,fileUrl)
      // const txCOs: any = await upToTxCos(render, fileUrl);
      // console.log(txCOs);

      ctx.body = {
        ...Exception(200, "上传成功"),
        data: {
          url: ctx.header.origin + filePath,
          // url: "http://qiniu.jackweb.cc/" + qiniu?.key,
          // url: aliOss.url,
          // url: txCOs.Location,
        },
      };
    } catch (error) {
      console.log(error);

      ctx.body = {
        ...Exception(112, "上传失败"),
        data: error,
      };
    }
  }
}
